<?php
declare (strict_types = 1);

namespace app\auth\service;

use app\auth\model\RoleModel;

class RoleService  extends BaseService
{
    public function __construct(RoleModel $roleModel, RightService $rightService)
    {
        $this->roleModel = $roleModel;
        $this->rightService = $rightService;
    }

    public function model(){
        return $this->roleModel;
    }

    public function list(array $where = [] , array $limit = [], array $sort= [], array $whereIn = []){
        $limit = check_limit($limit);
        $sort = check_sort($sort);
        $model = $this->roleModel;
        $model = $model::with([RoleModel::WITH_DEPT, RoleModel::WITH_RIGHTS]);
        $model = $model->where($where);
        $model = $model->limit($limit['page'],$limit['pagesize']);
        $model = $model->order($sort[0],$sort[1]);
        if(!empty($whereIn)) $model = $model->whereIn($whereIn[0],$whereIn[1]);
        $list = $model->select();
        if($list) $list = $list->toArray();
        //获取权限表
        $right_tree = $this->rightService->rightTree();
        foreach ($list as $index => $item){
            $right_ids = [];
            foreach ($item['rights'] as $right)
                $right_ids[] = $right['right_id'];
            //获取管理员的按钮
            $item['rights'] = $this->rightService->rightTreeFilter($right_tree, $right_ids);
            $list[$index] = $item;
        }
        return $list;

    }

    public function count(array $where = []){
        return $this->roleModel->where($where)->count();
    }

    public function insertGetId(array $data = []){
        return $this->roleModel->insertGetId($data);
    }

    public function update(array $where = [],array $data = []){
        return $this->roleModel->where($where)->update($data);
    }

    public function delete(array $whereIn = []){
        return $this->roleModel->whereIn($whereIn[0],$whereIn[1])->delete();
    }
}
